var express = require('express');
var router = express.Router();
const bannerCollection = require("../sql/banner");
const sql = require("../sql/sql");
const uuid = require("uuid");
const fs=require("fs");
const path=require("path");

/* GET users listing. */
router.get('/', function(req, res, next) {
  sql.getData(bannerCollection).then(data=>{
    console.log(data);
    res.render("banner",{
      index:2,
      power:req.session.power,
      data
    });
  })
  
});

router.post('/addAction',function(req,res,next){
  req.files.forEach(val=>{
    let oldName=val.path;
    let newName=(val.path+'-'+val.originalname).split('\\');
    newName=newName.join('/')
    fs.renameSync(oldName,newName)
    console.log('newname',newName);

    let serverPath = "http://localhost:5000/" + newName.replace("public/","");

    sql.addData(bannerCollection,{
      bannerId:"banner-" + uuid.v1(),
      name:req.body.imgName,
      title:req.body.imgTitle,
      src:serverPath,
      time:Date.now(),
      author:req.session.userName
    }).then(()=>{
      res.redirect('/banner')
    })

  })
})

router.get('/del',function(req,res,next){
  sql.delData(bannerCollection,{bannerId:req.query.id}).then(()=>{
    res.redirect('/banner')
  })
})

module.exports = router;
